
import * as MD5 from "md5";
import axios from "axios";
import { workspace, window } from "vscode";

const appid = workspace.getConfiguration().get('fanyiZh.baidu.appid');
const secret = workspace.getConfiguration().get('fanyiZh.baidu.secret');


/**
   * 翻译接口 目前调用百度翻译
   * @param {string} q -翻译内容
   */
export const getFanyi = async (q:string) : Promise<string | Array<null | {src:string,dst:string}>> => {
  if(!appid || !secret) {
    window.showWarningMessage('需要配置fanyiZh.baidu.appid和fanyiZh.baidu.secret');
    return '';
  }

  let from = 'en';
  let to = 'zh';
  const rex = /[\u4E00-\u9FA5]/g;
  const per = (q.match(rex)?.length || 0) / q.length > 0.4;
  if(per){
    from = 'zh';
    to = 'en';
  }
  const salt = Math.floor(Math.random() * 1000000000);
  const sign = MD5(appid + q + salt + secret);
  const params = `q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}&dict=1`;
  const url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?' + params;
  let res;
  try {
    const r = await axios(url);
    if(r.status === 200){
      if(r.data.error_msg){
        window.showErrorMessage(r.data.error_msg);
      }
      res = r.data?.trans_result || [];
    }else{
      res = '未知错误';
    }
  } catch (error) {
    res = JSON.stringify(error); 
  }
  return res;
};